package com.mdlaser.sys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mdlaser.enums.StatusType;
import com.mdlaser.exception.RestException;
import com.mdlaser.sys.dto.LoginDto;
import com.mdlaser.sys.entity.User;
import com.mdlaser.sys.mapper.UserMapper;
import com.mdlaser.sys.service.IUserService;
import com.mdlaser.util.EncryptionUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zn
 * @since 2024-04-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public void addUser(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, user.getUserName());
        List<User> users = this.getBaseMapper().selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(users)) {
            throw new RestException("用户已存在");
        }
        String password = user.getPassWord();
        user.setPassWord(EncryptionUtil.encryption(password));
        user.setStatus(StatusType.NORMAL.getValue());
        this.getBaseMapper().insert(user);
    }

    @Override
    public User getUserById(String userId) {
        return this.getBaseMapper().selectById(userId);
    }

    @Override
    public String login(LoginDto loginDto) {
        String userName = loginDto.getUserName();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);
        User user = this.getBaseMapper().selectOne(queryWrapper);
        boolean validate = false;
        if (user != null) {
            String userPwd = EncryptionUtil.decryption(user.getPassWord());
            validate = Objects.equals(loginDto.getPassWord(), userPwd);
        }
        if (user == null || !validate) {
            throw new RestException("用户名密码有误");
        }
        return user.getId();
    }
}
